package com.licq.ldoc.writer.visitor.example;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.licq.ldoc.utils.ClassUtils;

/**
 * 
 * @author liujian
 *
 */
public abstract class ExampleContext {
	private static transient Log logger = LogFactory.getLog(ExampleContext.class);
	
	private static Map<Class<?>, Object> examples = new HashMap<Class<?>, Object>();
	
	public static void set(Object example) {
		Class<?> clazz = example.getClass();
		if (examples.containsKey(clazz)) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format(
						"context already contains example with class[%s], it will be covered.", 
						clazz.getName()
					)
				);
			}
		}
		examples.put(clazz, example);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T get(Class<? extends T> clazz) {
		if (examples.containsKey(clazz)) {
			return (T) examples.get(clazz);
		} else {
			try {
				return ClassUtils.newInstance(clazz);
			} catch (Exception e) {
				if (logger.isInfoEnabled()) {
					logger.info(
						String.format(
							"create example with class[%s] failed.", 
							clazz.getName()
						),
						e	
					);
				}
				return null;
			}
		}
	}
	
	public static void main(String[] args) {
		
	}
	
}
